package com.gem.controller;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gem.domain.JobAPI;
import com.gem.domain.StuCareer;
import com.gem.service.CareerService;
import com.gem.util.ExcelUtil;
import com.gem.util.MessageUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CareerController {

    @Autowired
    CareerService careerService;


    /**
     * 默认就业信息跳转路径
     */
    @RequestMapping("/career/class/job")
    public String show(Model model, Integer careerClassId, String careerClassName) {
        List<StuCareer> pageBean = careerService.showStuCareer(careerClassId, null, null);
        model.addAttribute("pageBean", pageBean);
        model.addAttribute("careerClassId", careerClassId);//班级id
        model.addAttribute("careerClassName", careerClassName);//班级名
        return "career/info_job";
    }


    //搜索信息
    @RequestMapping("/career/class/searchCareer")
    public String searchClass(Model model, StuCareer stuCareer) {
        try {
            String careerStuName = stuCareer.getCareerStuName();
            String careerCompany = stuCareer.getCareerCompany();
            String careerCity = stuCareer.getCareerCity();

//      这里带本页面的实体的班级id
            Integer careerClassId = stuCareer.getCareerClassId();

            List<StuCareer> pageBean = careerService.searchStuCareer(stuCareer, null, null);
            System.out.println("就业信息查询结果:" + pageBean);
            if (pageBean != null) {
                model.addAttribute("pageBean", pageBean);
                model.addAttribute("searchUrl", "/career/class/searchCareer");
                model.addAttribute("careerStuName", careerStuName);
                model.addAttribute("careerCompany", careerCompany);
                model.addAttribute("careerCity", careerCity);
                model.addAttribute("careerClassId", careerClassId);
            } else {
                model.addAttribute("info", "暂无信息记录");
            }
            return "career/info_job";
        } catch (Exception e) {
            e.printStackTrace();
        }
        MessageUtil.returnInfoPage("3", "/career/findAll", "服务器异常，请联系管理员哦！", model);
        return "message";
    }

    //保存就业信息的修改
    @RequestMapping("/career/class/updateStuCareer")
    @Transactional//事务全部成功才生效
    public String updateStuCareer(Model model, String careerClassName, Integer careerClassId, Integer[] sid, String[] careerStuName, Integer[] careerIsCareer, String[] careerCity, String[] careerCompany, String[] careerJob, Double[] careerInternship, Double[] careerSalary, String[] careerTeacher, String[] careerWelfare, String[] careerRemarks) {
        try {
            model.addAttribute("careerClassName", careerClassName);

            System.out.println("控制层保存班级id1是" + careerClassId);

            JobAPI jobAPI = new JobAPI();
            StuCareer stuCareer = new StuCareer();
            List<JobAPI> jobAPIList = new ArrayList<>();
            for (int i = 0; i < sid.length; i++) {
                jobAPI.setSid(sid[i]);
                stuCareer.setSid(sid[i]);

                jobAPI.setCareerStuName(careerStuName[i]);
                stuCareer.setCareerStuName(careerStuName[i]);

                jobAPI.setCareerIsCareer(careerIsCareer[i]);
                stuCareer.setCareerIsCareer(careerIsCareer[i]);

                jobAPI.setCareerCity(careerCity[i]);
                stuCareer.setCareerCity(careerCity[i]);

                jobAPI.setCareerCompany(careerCompany[i]);
                stuCareer.setCareerCompany(careerCompany[i]);

                jobAPI.setCareerJob(careerJob[i]);
                stuCareer.setCareerJob(careerJob[i]);


                jobAPI.setCareerInternship(careerInternship[i]);
                stuCareer.setCareerInternship(careerInternship[i]);

                jobAPI.setCareerSalary(careerSalary[i]);
                stuCareer.setCareerSalary(careerSalary[i]);

                jobAPI.setCareerTeacher(careerTeacher[i]);
                stuCareer.setCareerTeacher(careerTeacher[i]);

                jobAPI.setCareerWelfare(careerWelfare[i]);
                stuCareer.setCareerWelfare(careerWelfare[i]);

                jobAPI.setCareerRemarks(careerRemarks[i]);
                stuCareer.setCareerRemarks(careerRemarks[i]);

                careerService.updateStuCareer(stuCareer);


                jobAPIList.add(jobAPI);
            }
            String json = JSON.toJSONString(jobAPIList);
            HttpHeaders headers = new HttpHeaders();
            Boolean result = HttpPost(json, headers);
            System.out.println("控制层保存班级id2是" + careerClassId);
            if(result){
                System.out.println("同步就业信息成功");//   做一个页面
            }

            MessageUtil.returnInfoPage("3", "/career/class/job?careerClassId=" + careerClassId, "修改成功！", model);
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/career/findAll", "服务器内部错误！请联系管理员！", model);
        }

        return "message";

    }

    //保存信息的界面控制
    @RequestMapping("/career/updateStuCareerUI")
    public String updateUI(Model model, Integer careerClassId, String careerClassName) {
        try {
            model.addAttribute("careerClassName", careerClassName);
            List<StuCareer> pageBean = careerService.showStuCareer(careerClassId, null, null);
            model.addAttribute("pageBean", pageBean);
            model.addAttribute("careerClassId", careerClassId);
        } catch (Exception e) {
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/career/findAll", "服务器异常！请联系管理员！", model);
            return "message";
        }
        System.out.println("班级id带入成功:" + careerClassId);
        return "career/job_update";
    }
    public static Boolean HttpPost(String json, HttpHeaders headers){
        String url = "http://114.55.144.40:8850/factory/updateJob";
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        RestTemplate rt = new RestTemplate();

        rt.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        ResponseEntity<Map> res = rt.postForEntity(url, json, Map.class);
        System.out.println(res.getBody());
        return (Boolean) res.getBody().get("0");
    }


//    //
//    @RequestMapping("/career/updateById")
//    public String updateById(Integer careerId, Model model) {
//
//        try {
//
//            StuCareer stuCareer = careerService.findById(careerId);
//            model.addAttribute("stuCareer", stuCareer);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            MessageUtil.returnInfoPage("3", "/campus/infoFindAll", "服务器异常！请联系管理员！", model);
//            return "message";
//        }
//        return "career/info_job_update";
//    }



    //导出就业信息excel模板
    @RequestMapping("/career/exportCareerTemplate")
    public void exportCareerExcelTemplate(Integer careerClassId,String careerClassName,HttpServletResponse response) throws Exception {
        //创建excel工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();


        //创建水平垂直居中的cellStyle单元格样式对象
        HSSFCellStyle cellStyle = ExcelUtil.getTitleStyle(workbook);

        //创建水平垂直居中加粗的cellStyle单元格样式,给表头试用
        HSSFCellStyle cellStyle2 = ExcelUtil.getThStyle(workbook);

        // 单元格类型日期格式化
        HSSFCellStyle cellStyleDate = ExcelUtil.getDateStyle(workbook);
        //创建行对象
        HSSFRow row = null;

        //我的院校
        //创建sheet对象
        HSSFSheet sheet = workbook.createSheet("就业信息表");

        // 将第一行的三个单元格给合并,模板固定
        //注意 java的参数是从0开始 即表示excel中的一行或者第一列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));
        row = sheet.createRow(0);
        HSSFCell beginCell0 = row.createCell(0);
        beginCell0.setCellValue( careerClassName+"  班级就业信息表");
        //cellStyle为水平居中字体加粗单元格样式
        beginCell0.setCellStyle(cellStyle);

        HSSFRow headRow = sheet.createRow(2);
        headRow.createCell(0).setCellValue("学生id");
        headRow.createCell(1).setCellValue("学生姓名");
        headRow.createCell(2).setCellValue("是否就业");
        headRow.createCell(3).setCellValue("就业城市");
        headRow.createCell(4).setCellValue("就业公司");
        headRow.createCell(5).setCellValue("职位");
        headRow.createCell(6).setCellValue("实习工资");
        headRow.createCell(7).setCellValue("正式工资");
        headRow.createCell(8).setCellValue("推荐老师");
        headRow.createCell(9).setCellValue("福利待遇");
        headRow.createCell(10).setCellValue("备注");


        headRow.setHeightInPoints(25); // 设置行的高度
        for (int i = 0; i < 11; i++) {
            headRow.getCell(i).setCellStyle(cellStyle2);
        }

        //创建水平垂直居中加粗的cellStyle单元格样式,给数据试用
        HSSFCellStyle rowStyle = ExcelUtil.getCenterStyle(workbook);

        //调用service方法查询所有数据集合

        List<StuCareer> careerList = careerService.showStuCareer(careerClassId, null, null);

        //优化 降低冗余
        HSSFCell cell = null;
        StuCareer stuCareer = null;

        String[] courseGradeArr = {"是", "否"};
        sheet = ExcelUtil.setHSSFValidation(sheet, courseGradeArr, 3, 300, 2, 2);

        //设置所有列列宽
        for (int i = 0; i < 11; i++) {
            sheet.setColumnWidth(i, 20 * 256);
        } // 设置列的宽度

        for (int i = 0; i < careerList.size(); i++) {
            row = sheet.createRow(i + 3);
            stuCareer = careerList.get(i);
            //第一列 学生id
            cell = row.createCell(0);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(stuCareer.getSid());

            //第二列 学生姓名
            cell = row.createCell(1);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(stuCareer.getCareerStuName());

//            //第三列 是否就业
//            cell = row.createCell(2);
//            cell.setCellStyle(rowStyle);
//            cell.setCellValue("是");







//            //第四列 就业城市
//            cell = row.createCell(3);
//            cell.setCellStyle(cellStyleDate);//改单元格为日期样式
//            cell.setCellValue(stuCareer.getCareerCity());//赋值
//            //第五列 就业公司
//            cell = row.createCell(4);
//            cell.setCellStyle(cellStyleDate);//改单元格为日期样式
//            cell.setCellValue(stuCareer.getCareerCompany());//赋值
//
//            //第六列 职位
//            cell = row.createCell(5);
//            cell.setCellStyle(rowStyle);
//            cell.setCellValue(stuCareer.getCareerJob());
//
//            //第七列 实习工资
//            cell = row.createCell(6);
//            cell.setCellStyle(rowStyle);
//            cell.setCellValue(stuCareer.getCareerInternship());
//
//            //第八列 正式工资
//            cell = row.createCell(7);
//            cell.setCellStyle(rowStyle);
//            cell.setCellValue(stuCareer.getCareerSalary());
//
//            //第九列 推荐老师
//            cell = row.createCell(8);
//            cell.setCellStyle(rowStyle);
//            cell.setCellValue(stuCareer.getCareerTeacher());
//
//            //第十列 福利待遇
//            cell = row.createCell(9);
//            cell.setCellStyle(rowStyle);
//            cell.setCellValue(stuCareer.getCareerWelfare());
//
//            //第十一列 备注
//            cell = row.createCell(10);
//            cell.setCellStyle(rowStyle);
//            cell.setCellValue(stuCareer.getCareerRemarks());

        }

        OutputStream outputStream = response.getOutputStream();
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=JobInfotemp.xls");

        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }






    //导出就业信息数据
    @RequestMapping("/career/exportCareer")
    public void exportCareerExcel(Integer careerClassId,String careerClassName,HttpServletResponse response) throws Exception {
        //创建excel工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();


        //创建水平垂直居中的cellStyle单元格样式对象
        HSSFCellStyle cellStyle = ExcelUtil.getTitleStyle(workbook);

        //创建水平垂直居中加粗的cellStyle单元格样式,给表头试用
        HSSFCellStyle cellStyle2 = ExcelUtil.getThStyle(workbook);

        // 单元格类型日期格式化
        HSSFCellStyle cellStyleDate = ExcelUtil.getDateStyle(workbook);
        //创建行对象
        HSSFRow row = null;

        //我的院校
        //创建sheet对象
        HSSFSheet sheet = workbook.createSheet("就业信息表");

        // 将第一行的三个单元格给合并,模板固定
        //注意 java的参数是从0开始 即表示excel中的一行或者第一列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));
        row = sheet.createRow(0);
        HSSFCell beginCell0 = row.createCell(0);
        beginCell0.setCellValue(careerClassName + "  班级就业信息表");
        //cellStyle为水平居中字体加粗单元格样式
        beginCell0.setCellStyle(cellStyle);

        HSSFRow headRow = sheet.createRow(2);
        headRow.createCell(0).setCellValue("学生id");
        headRow.createCell(1).setCellValue("学生姓名");
        headRow.createCell(2).setCellValue("是否就业");
        headRow.createCell(3).setCellValue("就业城市");
        headRow.createCell(4).setCellValue("就业公司");
        headRow.createCell(5).setCellValue("职位");
        headRow.createCell(6).setCellValue("实习工资");
        headRow.createCell(7).setCellValue("正式工资");
        headRow.createCell(8).setCellValue("推荐老师");
        headRow.createCell(9).setCellValue("福利待遇");
        headRow.createCell(10).setCellValue("备注");


        headRow.setHeightInPoints(25); // 设置行的高度
        for (int i = 0; i < 11; i++) {
            headRow.getCell(i).setCellStyle(cellStyle2);
        }

        //创建水平垂直居中加粗的cellStyle单元格样式,给数据试用
        HSSFCellStyle rowStyle = ExcelUtil.getCenterStyle(workbook);

        //调用service方法查询所有数据集合

        List<StuCareer> careerList = careerService.showStuCareer(careerClassId, null, null);

        //优化 降低冗余
        HSSFCell cell = null;
        StuCareer stuCareer = null;

        String[] courseGradeArr = {"是", "否"};
        sheet = ExcelUtil.setHSSFValidation(sheet, courseGradeArr, 3, 300, 2, 2);

        //设置所有列列宽
        for (int i = 0; i < 11; i++) {
            sheet.setColumnWidth(i, 20 * 256);
        } // 设置列的宽度

        for (int i = 0; i < careerList.size(); i++) {
            row = sheet.createRow(i + 3);
            stuCareer = careerList.get(i);
            //第一列 学生id
            cell = row.createCell(0);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(stuCareer.getSid());

            //第二列 学生姓名
            cell = row.createCell(1);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(stuCareer.getCareerStuName());

            //第三列 是否就业
            cell = row.createCell(2);
            cell.setCellStyle(rowStyle);
            cell.setCellValue((stuCareer.getCareerIsCareer() == 1)?"是":"否");



            //第四列 就业城市
            cell = row.createCell(3);
            cell.setCellStyle(cellStyleDate);//改单元格为日期样式
            cell.setCellValue(stuCareer.getCareerCity());//赋值
            //第五列 就业公司
            cell = row.createCell(4);
            cell.setCellStyle(cellStyleDate);//改单元格为日期样式
            cell.setCellValue(stuCareer.getCareerCompany());//赋值

            //第六列 职位
            cell = row.createCell(5);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(stuCareer.getCareerJob());

            //第七列 实习工资
            cell = row.createCell(6);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(stuCareer.getCareerInternship());

            //第八列 正式工资
            cell = row.createCell(7);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(stuCareer.getCareerSalary());

            //第九列 推荐老师
            cell = row.createCell(8);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(stuCareer.getCareerTeacher());

            //第十列 福利待遇
            cell = row.createCell(9);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(stuCareer.getCareerWelfare());

            //第十一列 备注
            cell = row.createCell(10);
            cell.setCellStyle(rowStyle);
            cell.setCellValue(stuCareer.getCareerRemarks());

        }

        OutputStream outputStream = response.getOutputStream();
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=JobInfo.xls");

        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }












    //导入院校excel数据到数据库
    @RequestMapping("/career/import")
    @Transactional(rollbackFor=Exception.class)
    public String importExcel(Integer careerClassId,@RequestParam("file") MultipartFile file, Model model) {
        try {
            //固定格式  参数file 为 文件上传的input的name
            HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet = workbook.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();

            StuCareer stuCareer = null;
            JobAPI jobAPI=null;
            HSSFRow row = null;

            List<JobAPI> jobAPIList = new ArrayList<>();


            //从第四行开始读取数据
            for (int i = 3; i <= lastRowNum; i++) {
                jobAPI = new JobAPI();
                stuCareer = new StuCareer();
                row = sheet.getRow(i);

                if (StringUtils.isEmpty(row.getCell(1).getStringCellValue()+"") && StringUtils.isEmpty(row.getCell(2).getStringCellValue())) {
                    break;//如果是空行无数据，停止写入
                }
                //学生id
                stuCareer.setSid((int) Math.ceil(row.getCell(0).getNumericCellValue()));
                jobAPI.setSid((int) Math.ceil(row.getCell(0).getNumericCellValue()));

                stuCareer.setCareerStuName(row.getCell(1).getStringCellValue());
                jobAPI.setCareerStuName(row.getCell(1).getStringCellValue());

                stuCareer.setCareerIsCareer((row.getCell(2).getStringCellValue().equals("是"))?1:0);
                jobAPI.setCareerIsCareer((row.getCell(2).getStringCellValue().equals("是"))?1:0);


                stuCareer.setCareerCity(row.getCell(3).getStringCellValue());
                jobAPI.setCareerCity(row.getCell(3).getStringCellValue());

                stuCareer.setCareerCompany(row.getCell(4).getStringCellValue());
                jobAPI.setCareerCompany(row.getCell(4).getStringCellValue());


                stuCareer.setCareerJob(row.getCell(5).getStringCellValue());
                jobAPI.setCareerJob(row.getCell(5).getStringCellValue());

                stuCareer.setCareerInternship((row.getCell(6).getNumericCellValue()));
                jobAPI.setCareerInternship((row.getCell(6).getNumericCellValue()));

                stuCareer.setCareerSalary((row.getCell(7).getNumericCellValue()));
                jobAPI.setCareerSalary((row.getCell(7).getNumericCellValue()));

                stuCareer.setCareerTeacher(row.getCell(8).getStringCellValue());
                jobAPI.setCareerTeacher(row.getCell(8).getStringCellValue());

                stuCareer.setCareerWelfare(row.getCell(9).getStringCellValue());
                jobAPI.setCareerWelfare(row.getCell(9).getStringCellValue());

                stuCareer.setCareerRemarks(row.getCell(10).getStringCellValue());
                jobAPI.setCareerRemarks(row.getCell(10).getStringCellValue());


                //添加一个对象,循环,直到结束
                careerService.updateStuCareer(stuCareer);
                jobAPIList.add(jobAPI);

            }
            String json = JSON.toJSONString(jobAPIList);
            HttpHeaders headers = new HttpHeaders();
            Boolean result = HttpPost(json, headers);
            System.out.println("控制层保存班级id2是" + careerClassId);
            if(result){
                System.out.println("同步导入就业信息成功");//   做一个页面
            }

            MessageUtil.returnInfoPage("3", "/career/class/job?careerClassId=" + careerClassId, "导入成功!", model);
        } catch(Exception e){
            e.printStackTrace();
            MessageUtil.returnInfoPage("3", "/career/class/job?careerClassId=" + careerClassId, "导入失败!请联系管理员！", model);
        }
        return "message";

    }


}